//对图片进行压缩
function compressimg(fileObj, callback) {
    if (typeof (FileReader) === 'undefined') {
        console.log("当前浏览器内核不支持base64图片压缩")
    } else {
        try {
            var reader = new FileReader();
            reader.onload = function (e) {
                var image = $('<img/>');
                image.load(function () {
                    var imageWidth = 600,//定义画布大小,也就是图片压缩之后的像素
                        canvas = document.createElement('canvas'),
                        context = canvas.getContext('2d');
                    let imageHeight = Math.ceil(imageWidth * this.height / this.width);
                    canvas.width = imageWidth;
                    canvas.height = imageHeight;
                    context.clearRect(0, 0, imageWidth, imageHeight);
                    context.drawImage(this, 0, 0, imageWidth, imageHeight);
                    var data = canvas.toDataURL('image/jpeg')
                    callback(data)
                });
                image.attr('src', e.target.result)
            };
            reader.readAsDataURL(fileObj);
        } catch (e) {
            console.log('压缩失败!')
        }
    }
}

//对图片放大,缩小,拖动,旋转
function biggerimg(e,showText=true) {
    var img = new Image();
    img.src = $(e).attr("src");
    var width = img.width, height = Math.ceil(width * img.height / img.width);
    var imgHtml = "<img id='bigimg' width='" + img.width + "' src='" + img.src + "' />";
    var index = layer.open({
        type: 1,
        shade: 0.8,
        title: false,
        area: ['auto', 'auto'],
        // area : ['100%', '100%'],
        shadeClose: true,//点击外围关闭弹窗
        content: imgHtml, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
    });
    if (showText) {
        let strwarn = '<h3 class="ml-20" style="color: #ffffff;">双击可旋转，长按滑动可拖动，滚轮滑动可缩放</h3>';
        $('.layui-layer-shade').html(strwarn);
    }
    //滚动变大缩小
    mouseZoomer(img);
    //点击旋转
    toRotate();
}
//滚动变大缩小
function mouseZoomer(img) {
    $('body').mousewheel(function (event, delta) {
        width = Number($('#bigimg').attr('width'));
        delta > 0 ? width += 100 : width -= 100;
        var dw = $(window).width();
        var wh = $(window).height();
        width > dw ? width = dw : width < 100 ? width = 100 : '';
        height = Math.ceil(width * img.height / img.width);
        let left = (dw - width) / 2;
        let top = (wh - height) / 2;
        $('#bigimg').attr('width', width).parents('.layui-layer-content').removeAttr('style').parents('.layui-layer-page').css('top', top).css('left', left);
    });
}

//点击旋转
function toRotate() {
    var current = 0;
    $("#bigimg").on({
        dblclick:function(){
            current = (current + 90) % 360;
            $(this).parents('.layui-layer-page').css('transform', 'rotate(' + current + 'deg)');
        },
        mousedown: function (e) {
            var el = $(this).parents('.layui-layer-page');
            var os = el.offset();
            dx = e.pageX - os.left, dy = e.pageY - os.top;
            $(document).on('mousemove.drag', function (e) {
                el.offset({top: e.pageY - dy, left: e.pageX - dx});
            });
        }, mouseup: function (e) {
            $(document).off('mousemove.drag');
        }
    })
}

//选择图片
function choseImgs(id, bar_code, pos='') {
    var imgHtml = "<div class='ml-20'><input accept='image/*'  class='mt-10' type='file' onclick='choseImgsUp()'/><br>" +
        "<span style='color:red;'>要求：</span>图片宽高比为4:3或3:4（建议直接用手机拍摄4:3图片，如果需要再用imark或小Q画笔对图片进行局部放大）<br>" +
        "<p class='ml-50'>上传图片预览：</p><div class='text-c'><img class='img-responsive fornonphoto' style='height:300px;' src='' onclick='biggerimg(this)'></div>" +
        "</div>";
    layer.open({
        type: 1,
        offset: 'auto',
        area: ['600px', '600px'],
        title: "上传照片", //不显示标题
        content: imgHtml, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
        btn: ['提交', '取消'],
        yes: function (index, layero) {
            if (isup === 0) {
                layer.msg('图片不符合要求，请重新上传');
                return false;
            }
            let base64data = $('.fornonphoto').attr('src');
            if (base64data === '') {
                layer.alert('请先上传新的照片');
                return false;
            }
            $.ajax({
                type: 'post',
                url: "/"+adminName+"/photo/list/sub",
                // dataType: 'json',
                headers:{
                    'X-CSRF-TOKEN': $('meta[name=csrf-token]').attr('content')
                },
                data: {
                    detail_id: id,
                    non_photo: base64data,
                    pos:pos,
                },
                success: function (data) {
                    // console.log(data);
                    if (data === '1') {
                        let img = '<div><img style="width:100%;" class="img-responsive radio" src="' + base64data + '" onclick="biggerimg(this)"> ' +
                            '<a onclick="imgdel(' + bar_code + ',this)" class="ml-5 btn btn-danger-outline radius size-MINI">删除</a></div>';
                        $('#non-photo-' + id).html(img)
                        layer.msg('图片上传成功!', {icon: 1, time: 1000});
                        layer.close(index);
                    } else {
                        layer.msg(data.msg ? data.msg : '图片上传失败!', {icon: 2, time: 2000});
                    }
                },
                error: function (data) {
                    ajax_error(data);
                },
                beforeSend: function () {
                    //0.4透明度 白色遮罩
                    index2 = layer.load(2, {shade: [0.05, '#000']});
                },
                complete: function () {
                    layer.close(index2);
                },
            });
        },
        cancel: function () {
            //右上角关闭回调
        }
    });
}

function choseImgsUp() {
    $(this).on('change', function (e) {
        var file = e.target.files[0],//拿到原始对象
            thisType = file.type,//获取到表面的名称，可判断文件类型
            reader = new FileReader(),
            img = e.target.nextSibling;
        if (thisType.indexOf('image/') !== 0) {
            layer.alert('该文件不是图片！');
            return false;
        }
        if (file.size > 500 * 1024) {
            //调用函数,对图片进行压缩
            compressimg(file, function (imgBase64) {
                $(img).attr('src', imgBase64);
            })
        }
        //readAsDataURL(file),读取文件，将文件以数据URL的形式保存在result的属性中
        reader.readAsDataURL(file);
        //文件加载成功以后，渲染到页面
        reader.onload = function (e) {
            $('.fornonphoto').attr('src', e.target.result).load(function () {/*如果要获取图片的真实的宽度和高度有三点必须注意1、需要创建一个image对象：如这里的$("")2、指定图片的src路径3、一定要在图片加载完成后执行如.load()函数里执行*/
                let realWidth = this.width, realHeight = this.height, bili = (realHeight / realWidth).toFixed(2);//如果真实的宽度大于浏览器的宽度就按照100%显示
                if ((bili < 0.77 && bili > 0.73) || (bili < 1.35 && bili > 1.31)) {
                    isup = 1;
                } else {
                    layer.msg('图片不符合要求');
                    isup = 0;
                    return false;
                }
            })
        }
    })
}

